/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: ModelCommClusterServiceImpl.java
 * Author:   13075787
 * Date:     2016年7月6日 上午11:04:06
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.service.impl.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.model.ModelClusterVo;
import com.suning.sawp.intf.model.ModelCommClusterVo;
import com.suning.sawp.intf.model.ModelCommodityBaseInfo;
import com.suning.sawp.intf.model.ModelConstant;
import com.suning.sawp.intf.model.ModelMainListBean;
import com.suning.sawp.intf.model.ModelZoneInfo;
import com.suning.sawp.intf.model.TaskBranchVo;
import com.suning.sawp.intf.model.TaskCateVo;
import com.suning.sawp.intf.model.TaskInfoVo;

/**
 * 样机管理-封装<br>
 * 商品簇管理
 *
 * @author 13075787
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service("modelCommClusterService")
public class ModelCommClusterServiceImpl {

    @Autowired
    ModelCommodityInfoServiceImpl modelCommodityInfoService;

    @Autowired
    ModelCommClusterDaoServiceImpl modelCommClusterDaoService;

    @Autowired
    ModelTaskDaoServiceImpl modelTaskDaoService;

    @Autowired
    ModelBlendDaoServiceImpl modelBlendDaoService;

    /**
     * 功能描述: <br>
     * 保存-添加商品簇-商品
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ReturnMsg addModelCommCluster(ModelZoneInfo modelZone, String commCode, String addCommCode) {
        ReturnMsg result = new ReturnMsg();
        result.setRetFlag(ReturnMsg.FAIL);
        if (StringUtils.isNotBlank(commCode) && StringUtils.isNotBlank(addCommCode)) {
            if (!commCode.equals(addCommCode)) {
                ModelCommodityBaseInfo comm = modelCommodityInfoService.queryCommodityBaseInfo(commCode);
                if (!this.checkComm(comm)) {
                    // 该商品信息不存在 直接返回
                    result.setError(ModelConstant.MODEL_ERROR_NO_COMM,
                            commCode + ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_COMM));
                    return result;
                }
                ModelCommodityBaseInfo addComm = modelCommodityInfoService.queryCommodityBaseInfo(addCommCode);
                if (!this.checkComm(addComm)) {
                    // 该商品信息不存在 直接返回
                    result.setError(ModelConstant.MODEL_ERROR_NO_COMM,
                            addCommCode + ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_COMM));
                    return result;
                }
                String retCluster = modelCommClusterDaoService.addModelCommCluster(modelZone, comm, addComm);
                if (StringUtils.isNotBlank(retCluster)) {
                    result.setRetFlag(ReturnMsg.SUCCESS);
                    result.setData(retCluster);
                }
            } else {
                // 编码相同
                result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                        "商品编码不能相同:" + ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
            }
        } else {
            result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                    ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
        }
        return result;
    }

    /**
     * 判断该商品信息有效
     */
    private boolean checkComm(ModelCommodityBaseInfo comm) {
        boolean result = false;
        if (null != comm && StringUtils.isNotBlank(comm.getCommCode())) {
            result = true;
        }
        return result;
    }

    /**
     * 功能描述: <br>
     * 删除某个簇中的商品
     * 
     * @param storeMan
     * @param commCode
     * @param delCommCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("rawtypes")
    public ReturnMsg delModelCommCluster(StoreManDto storeMan, String commCode, String delCommCode) {
        ReturnMsg result = new ReturnMsg();
        result.setRetFlag(ReturnMsg.FAIL);
        if (StringUtils.isNotBlank(commCode) && StringUtils.isNotBlank(delCommCode)) {
            if (!commCode.equals(delCommCode)) {
                if (modelCommClusterDaoService.deleteClusterComm(storeMan.getBranchCode(), commCode, delCommCode)) {
                    result.setRetFlag(ReturnMsg.SUCCESS);
                }
            } else {
                // 编码相同
                result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                        "商品编码不能相同:" + ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
            }
        } else {
            result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                    ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
        }
        return result;
    }

    /**
     * 功能描述: <br>
     * 查询指定的商品的簇列表商品信息（排除指定查询的商品本身）
     * 
     * @param storeMan
     * @param commCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ReturnMsg<List<ModelCommClusterVo>> queryModelCommClusters(StoreManDto storeMan, String commCode) {
        ReturnMsg<List<ModelCommClusterVo>> result = new ReturnMsg<List<ModelCommClusterVo>>();
        result.setRetFlag(ReturnMsg.SUCCESS);
        if (StringUtils.isBlank(commCode)) {
            result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                    ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
            return result;
        }
        List<ModelCommClusterVo> list = modelCommClusterDaoService.queryModelCommClusters(storeMan.getBranchCode(),
                commCode);
        // 去除要查询的商品本身
        List<ModelCommClusterVo> retList = new ArrayList<ModelCommClusterVo>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ModelCommClusterVo modelCommClusterVo : list) {
                if (null != modelCommClusterVo && !commCode.equals(modelCommClusterVo.getCommCode())) {
                    ModelCommClusterVo loc = new ModelCommClusterVo();
                    loc.setCommCode(modelCommClusterVo.getCommCode());
                    loc.setCommName(modelCommClusterVo.getCommName());
                    retList.add(loc);
                }
            }
        }
        result.setData(retList);
        
        return result;
    }

    /**
     * 功能描述: <br>
     * 查询指定商品编码的推荐商品簇商品列表（去除已添加到该商品簇中）
     *
     * @param storeMan
     * @param commCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ReturnMsg<List<ModelCommClusterVo>> queryRecommendModelCommClusters(StoreManDto storeMan, String commCode) {
        ReturnMsg<List<ModelCommClusterVo>> result = new ReturnMsg<List<ModelCommClusterVo>>();
        result.setRetFlag(ReturnMsg.SUCCESS);
        if (StringUtils.isBlank(commCode)) {
            result.setError(ModelConstant.MODEL_ERROR_NO_PARAM,
                    ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_PARAM));
            return result;
        }
        List<ModelCommClusterVo> list = modelCommClusterDaoService.queryModelCommClusters(storeMan.getBranchCode(),
                commCode);
        // 查询商品中心该商品的商品簇列表
        List<ModelCommodityBaseInfo> recList = modelCommodityInfoService.queryCommodityCluster(commCode);
        // 该商品簇中已有的商品编码放入到如下集合中
        HashSet<String> existSet = new HashSet<String>();
        existSet.add(commCode);
        if (CollectionUtils.isNotEmpty(list)) {
            for (ModelCommClusterVo modelCommCluster : list) {
                if (null != modelCommCluster) {
                    existSet.add(modelCommCluster.getCommCode());
                }
            }
        }
        // 去除已经添加到该商品簇的商品
        List<ModelCommClusterVo> retList = new ArrayList<ModelCommClusterVo>();
        if (CollectionUtils.isNotEmpty(recList)) {
            for (ModelCommodityBaseInfo commodityBase : recList) {
                if (null != commodityBase && !existSet.contains(commodityBase.getCommCode())) {
                    ModelCommClusterVo loc = new ModelCommClusterVo();
                    loc.setCommCode(commodityBase.getCommCode());
                    loc.setCommName(commodityBase.getCommName());
                    retList.add(loc);
                }
            }
        }
        result.setData(retList);
        
        return result;
    }

    /**
     * 查询-簇维护任务的商品列表 queryHandleTask
     */
    @Deprecated
    public ReturnMsg<List<ModelClusterVo>> queryMaintainClusterCommList(StoreManDto storeMan, Long taskId,
            Integer index, Integer size) {
        ReturnMsg<List<ModelClusterVo>> result = new ReturnMsg<List<ModelClusterVo>>();
        /*
        List<ModelClusterVo> clusterList = new ArrayList<ModelClusterVo>();
        result.setData(clusterList);
        String storeCode = storeMan.getStoreCode();
        String staffId = storeMan.getStaffId();
        // 1查询出任务-遍历出要维护簇商品的品牌列表
        List<TaskInfoVo> tasks = modelTaskDaoService.queryHandleTask(taskId, storeCode, staffId,
                ModelConstant.TASK_TYPE_CLUSTER);
        if (CollectionUtils.isNotEmpty(tasks) && null != tasks.get(ModelConstant.NUM_ZERO)) {
            TaskInfoVo taskInfo = tasks.get(ModelConstant.NUM_ZERO);
            List<String> brandCodes = this.getBrandCodeFromTaskInfo(taskInfo);
            // 2根据以上信息从样机清单中查询出满足条件的商品
            if (null != taskInfo && CollectionUtils.isNotEmpty(brandCodes)) {
                List<ModelMainListBean> comms = modelBlendDaoService.queryModelCommInfo(storeCode, brandCodes,
                        taskInfo.getStorageCode(), index, size);
                // 3遍历上面的商品，查询出各个商品的簇数量
                if (CollectionUtils.isNotEmpty(comms)) {
                    List<String> commCodes = Lists
                            .newArrayList(Lists.transform(comms, new Function<ModelMainListBean, String>() {
                                @Override
                                public String apply(ModelMainListBean input) {
                                    String result = input.getCommCode();
                                    return result;
                                }
                            }));
                    // 获取该商品列表簇数量
                    Integer[] counts = modelCommClusterDaoService.queryModelCommClusterCount(storeMan.getBranchCode(),
                            commCodes);
                    // 转为结果
                    for (int i = 0; i < commCodes.size(); i++) {
                        ModelMainListBean modelComm = comms.get(i);
                        ModelClusterVo clusterVo = new ModelClusterVo();
                        clusterVo.setCommName(modelComm.getCommName());
                        clusterVo.setCommCode(modelComm.getCommCode());
                        clusterVo.setClusterNum(counts[i]);
                        clusterVo.setClusterFlag(counts[i] > ModelConstant.NUM_ONE ? ModelConstant.CLUSTER_FLAG_TRUE
                                : ModelConstant.CLUSTER_FLAG_FALSE);
                        clusterList.add(clusterVo);
                    }
                }
            }
        } else {
            // 该员工没有此任务
            result.setError(ModelConstant.MODEL_ERROR_NO_TASK,
                    ModelConstant.getErrorValue(ModelConstant.MODEL_ERROR_NO_TASK));
        }*/
        return result;
    }

    /**
     * 功能描述: <br>
     * 从任务中分离出9位品类编码
     * 
     * @param taskInfo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<String> getBrandCodeFromTaskInfo(TaskInfoVo taskInfo) {
        List<String> result = null;
        if (null != taskInfo && CollectionUtils.isNotEmpty(taskInfo.getCates())) {
            result = new ArrayList<String>();
            for (TaskCateVo taskCateVo : taskInfo.getCates()) {
                for (TaskBranchVo taskBranchVo : taskCateVo.getBranchs()) {
                    result.add(taskBranchVo.getBranch9Code());
                }
            }
        }
        return result;
    }

}
